<template>
  <el-dialog v-model="dialogVisible" title="" width="30%" :show-close="true" :center="true" :close-on-press-escape="false"
    :close-on-click-modal="false">
    <h1 style="text-align: center">{{ payWay === '1' ? '请微支付宝码支付' : '请微信扫码支付' }}</h1>
    <br />
    <qrcode-vue :value="qrcodeUrl" :size="300" style="margin-left: 116px"></qrcode-vue>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import VueCookies from 'vue-cookies'
import QrcodeVue from 'qrcode.vue'
import mitt from '@/utils/mitt'

const cookie: any = VueCookies
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['changeIsShow'])
const dialogVisible = ref(false)
const qrcodeUrl = ref('')
const payWay = ref('1')
const t = cookie.get('token')

const wsServer = `ws://172.16.10.160:81/v1/user/balance/recharge?token=${t}`
const websocket = new WebSocket(wsServer)

websocket.onopen = (evt) => {
  watch(
    () => props.isShow,
    (n: any) => {
      dialogVisible.value = n
      if (n) {
        payWay.value = JSON.parse(sessionStorage.getItem('ruleForm') as string).paymentMethod

        websocket.send(sessionStorage.getItem('ruleForm') as string)
      }
    }
  )
}
websocket.onmessage = function (evt) {
  console.log('服务器端消息: ' + evt.data)
  if (evt.data) {
    const msg = JSON.parse(evt.data)
    console.log(msg)
    if (msg.msg) {
      if (msg.code === '0') {
        ElMessage.success('充值成功！')
        emit('changeIsShow')
        mitt.emit('queryBalance')
        // 跳转充值记录
        mitt.emit('handleUpdateCurrentMenu', 'rechageRecord')
      } else {
        ElMessage.error(msg.msg)
      }
    } else {
      qrcodeUrl.value = msg.codeUrl
    }
  }
}
websocket.onclose = function (evt) {
  console.log('断开连接')
}

</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
